package cn.itcast.bos.web.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.itcast.bos.domain.base.Standard;
import cn.itcast.bos.service.StandardService;

@ParentPackage("json-default")
@Namespace("/")
@Actions // 用于配置多个Action
@Controller
@Scope("prototype") // Action是多例的,每一次发送一个新的请求时就会创建一个相应的Action对象
public class StandardAction extends ActionSupport implements ModelDriven<Standard> {

	@Autowired
	private StandardService standardService;

	// 模型驱动
	private Standard standard = new Standard();

	@Override
	public Standard getModel() {
		return standard;
	}

	
	@Action(value="standard_findAll",
			results={@Result(name="success",type="json")})
	public String findAll(){
		List<Standard> list = standardService.findAll();
		
		ActionContext.getContext().getValueStack().push(list);
		return SUCCESS;
	}
	
	
	// 属性驱动 pageQuery分页查询请求从页面发送过来的page和rows属性的封装
	private int page;
	private int rows;
	
	public void setPage(int page) {
		this.page = page;
	}
	
	public void setRows(int rows) {
		this.rows = rows;
	}
	//分页列表查询
	@Action(value = "standard_pageQuery", results = {
			@Result(name = "success", type = "json")})
	public String pageQuery() {
		// 利用Pageable接口封装请求参数
		// 		在Pageable的实现类PageRequest类中定义的当前页码是zero-based,
		//  而我们从页面传入的数据中页码是从1开始计数的,所以这里的page需要进行-1的操作
		Pageable pageable = new PageRequest(page - 1, rows);

		// 调用业务层进行查询
		Page<Standard> page = standardService.pageQuery(pageable);

		// 将page中所需要的数据存到一个map集合当中(要求存入到值栈的数据必须以键值形式出现)
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("total", page.getTotalElements());
		map.put("rows", page.getContent());
		
		// 将map集合压入值栈栈顶,struts2-json-plugin插件会自动将栈顶的数据转换为json数据类型
		ActionContext.getContext().getValueStack().push(map);

		return SUCCESS;
	}

	@Action(value = "standard_save", results = {
			@Result(name = "success", type = "redirect", location = "./pages/base/standard.html") })
	// 做增加、修改、删除的操作，需要加上type="redirect"，查询时不用
	public String save() {
		standardService.save(standard);
		return SUCCESS;
	}

}
